package JUC.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {

    //CAS
    public static void main(String[] args) {
        //期望值
        //AtomicInteger atomicInteger=new AtomicInteger(2020);

        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1, 1);

        //模拟两个线程操作
        //每次操作前获得版本号
        //泛型是包装类，范围只能在-128~127,不然会有对象引用问题。
        new Thread(()->{
            int stamp =atomicInteger.getStamp();
            System.out.println("a1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            atomicInteger.compareAndSet(1,2,atomicInteger.getStamp(),atomicInteger.getStamp()+1);
            System.out.println("a2=>"+stamp);

            atomicInteger.compareAndSet(2,1,atomicInteger.getStamp(),atomicInteger.getStamp()+1);
            System.out.println("a3=>"+stamp);

        },"a").start();

        //和乐观锁原理相同
        new Thread(()->{
            int stamp =atomicInteger.getStamp();
            System.out.println("b1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            atomicInteger.compareAndSet(1,3,atomicInteger.getStamp(),atomicInteger.getStamp()+1);
            System.out.println("b1=>"+atomicInteger.getStamp());

        },"b").start();






        //参数:期望，更新
        //public final boolean compareAndSet(int expect, int update)
        //达到期望值就更新，否则不更新
        //==========捣乱的线程===========
//       System.out.println(atomicInteger.compareAndSet(2020, 2023));//期望值达到了就更新，否则就不更新
//       System.out.println(atomicInteger.get());
//
//       System.out.println(atomicInteger.compareAndSet(2021, 2020));//期望值达到了就更新，否则就不更新
//       System.out.println(atomicInteger.get());
//
//       //==========期望的线程==========
//       System.out.println(atomicInteger.compareAndSet(2020, 2021));//期望值达到了就更新，否则就不更新
//       System.out.println(atomicInteger.get());
    }
}